package com.hwadee.ems.service.impl;

import java.time.Year;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;

import org.springframework.stereotype.Service;

import com.hwadee.ems.domain.po.Class;
import com.hwadee.ems.domain.dto.Result;
import com.hwadee.ems.domain.dto.PageQuery;
import com.hwadee.ems.domain.po.TrainingProgram;
import com.hwadee.ems.domain.vo.TrainingProgramVO;
import com.hwadee.ems.mapper.TrainingProgramMapper;
import com.hwadee.ems.service.IUserService;
import com.hwadee.ems.service.IClassService;
import com.hwadee.ems.service.ITrainingProgramService;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * <p>
 * 培养方案 服务实现类
 * </p>
 *
 * @author EnosElinsa
 * @since 2024/06/21
 */
@Service
public class TrainingProgramServiceImpl extends ServiceImpl<TrainingProgramMapper, TrainingProgram> implements ITrainingProgramService {

    private static ITrainingProgramService instance;

    public static ITrainingProgramService getInstance() {
        return instance;
    }

    @PostConstruct
    void init() {
        instance = this;
    }

    @Resource
    private IUserService userService;

    @Resource
    private IClassService classService;

    @Override
    public Result<IPage<TrainingProgramVO>> page(PageQuery pageQuery) {
        return Result.ok(page(Page.of(pageQuery.getCurrent(), pageQuery.getSize()), 
            Wrappers.emptyWrapper()).convert(TrainingProgramVO::new));
    }

    @Override
    public Result<IPage<TrainingProgramVO>> pageByMajorId(Long majorId, PageQuery pageQuery) {
        var wrapper = Wrappers.lambdaQuery(TrainingProgram.class)
           .eq(TrainingProgram::getMajorId, majorId);  
        return Result.ok(page(Page.of(pageQuery.getCurrent(), pageQuery.getSize()), wrapper)
            .convert(TrainingProgramVO::new));
    }

    @Override
    public Result<TrainingProgramVO> getByStudentId(Long studentId) {
        Long classId = userService.getById(studentId).getClassId();
        Class classEntity = classService.getById(classId);
        Long majorId = classEntity.getMajorId();
        Year grade = classEntity.getGrade();
        TrainingProgram trainingProgram = lambdaQuery().eq(TrainingProgram::getMajorId, majorId)
            .eq(TrainingProgram::getGrade, grade)
            .one();
        TrainingProgramVO trainingProgramVO = new TrainingProgramVO(trainingProgram);
        return Result.ok(trainingProgramVO);
    }

}
